const baseURL = 'http://202.192.19.106:8080';

// 获取用户的 token
function getToken() {
  return wx.getStorageSync('userToken'); // 根据你的存储方式修改
}

function request(url, method = 'GET', data = {}, successCallback, errorCallback) {
   const token = getToken(); // 获取用户的 token

   console.log(token)
   console.log("request__function")
  // const token="eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyQ29udGV4dERUTyI6eyJpZCI6Miwic2Nob29sSWQiOjEsImdyYWRlSWQiOjIsImNsYXNzSWQiOjIsImNpdHlJZCI6MSwiZGlzdHJpY3RJZCI6Nywicm9sZUxldmVsIjo1MH0sImV4cCI6MTcyNzAxMzY2NH0.PW-ZUggGpPD7vnlP32lEbnV-U59AuynKKy6e4FXEhNA"

  wx.request({
    url: `${baseURL}${url}`,
    method: method,
    data: data,
    header: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`, // 添加 token 到请求头
      'X-Custom-Header': 'foobar' // 自定义头部
    },
    timeout: 20000,
    success(res) {
      if (res.statusCode === 200) {
        // 检查 API 返回的 code
        if (res.data.code === 200) {
          successCallback(res.data); // 调用成功回调
        } else {
          wx.showToast({
            title: res.data.msg || '服务异常',
            icon: 'none'
          });
          errorCallback(res.data); // 调用失败回调
         
        }
      } else {
        wx.showToast({
          title: '请求失败',
          icon: 'none'
        });
        errorCallback(res);
      }
    },
    fail(err) {
      wx.showToast({
        title: '请求失败',
        icon: 'none'
      });
      errorCallback(err); // 调用失败回调
      console.log("error from request")
      console.log("token from request")
      console.log("1",token)
    }
  });
}

const get = (url, data = {}, successCallback, errorCallback) => request(url, 'GET', data, successCallback, errorCallback);
const post = (url, data = {}, successCallback, errorCallback) => request(url, 'POST', data, successCallback, errorCallback);

export { get, post, baseURL };
